<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <!-- 引入vue.js库 -->
    <script src="/js/vue.js"></script>
    <!-- element-ui引入样式 展示数据-->
    <link rel="stylesheet" href="/css/index.css">
    <!-- element-ui引入组件库 -->
    <script src="/js/index.js"></script>
    <!-- 引入axios库 从后端获取数据-->
    <script src="/js/axios.min.js"></script>
    <!--上传头像-->
    <!--引入style-->
    <style>
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body>
<!--vue必须绑定根标签-->
<div id="app">
    <!--搜索-->
    <el-row>
        <!--一行分为4列-->
        <el-col :span="3">
            <el-input v-model="searchForm.userName" size="mini" placeholder="请输入用户昵称"></el-input>
        </el-col>
        <el-col :span="3">
            <el-input v-model="searchForm.remark" size="mini" placeholder="请输入备注"></el-input>
        </el-col>
        <el-col :span="2">
            <el-button type="success" icon="el-icon-search" size="mini" @click="search">搜索</el-button>
        </el-col>
        <el-col :span="2">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">添加</el-button>
        </el-col>
        <el-col :span="14">&nbsp;</el-col>
    </el-row>

    <!--table 数据-->
    <el-table
            :data="tableData"
            style="width: 100%">
        <el-table-column fixed prop="userId" label="编号" width="70">
        </el-table-column>
        <!-- <el-table-column prop="deptId" label="部门ID" width="70">
         </el-table-column>-->
        <el-table-column prop="loginName" label="登录账号" width="100">
        </el-table-column>
        <el-table-column prop="userName" label="用户昵称" width="100">
        </el-table-column>
        <el-table-column prop="userType" :formatter="getUserType" label="用户类型" width="100">
        </el-table-column>
        <el-table-column prop="email" label="用户邮箱" width="170">
        </el-table-column>
        <el-table-column prop="phoneNumber" label="手机号码" width="160">
        </el-table-column>
        <el-table-column prop="sex" :formatter="getSex" label="用户性别" width="100">
        </el-table-column>
        <!--<el-table-column prop="avatar" label="头像" width="270">
        </el-table-column>-->
        <el-table-column label="头像">
            <template slot-scope="scope">
                <el-image
                        style="width: 50px; height: 50px"
                        :src="scope.row.avatar"
                        :fit="fit">
                </el-image>
            </template>
        </el-table-column>
        <el-table-column prop="password" label="密码" width="270">
        </el-table-column>
        <!--<el-table-column prop="salt" label="盐加密" width="170">
        </el-table-column>-->
        <el-table-column prop="status" :formatter="getStatus" label="帐号状态" width="100">
        </el-table-column>
        <el-table-column prop="delFlag" :formatter="getDelFlag" label="删除标志" width="100">
        </el-table-column>
        <el-table-column prop="loginIp" label="最后登陆IP" width="150">
        </el-table-column>
        <el-table-column prop="loginDate" label="最后登陆时间" width="170">
        </el-table-column>
        <el-table-column prop="createBy" label="创建者" width="70">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170">
        </el-table-column>
        <el-table-column prop="updateBy" label="更新者" width="70">
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="170">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="160">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="330">
            <template slot-scope="scope">
                <el-button
                        size="mini"
                        @click="addRole(scope.$index, scope.row)">添加角色
                </el-button>
                <el-button
                        size="mini"
                        @click="handleEdit(scope.$index, scope.row)">编辑
                </el-button>
                <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)">删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!--分页功能-->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[2,5,10,15,20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>
    <!--角色授权弹出框-->
    <el-dialog title="角色列表" :visible.sync="rolesVisible">
        <template>
            <el-checkbox
                    :indeterminate="isIndeterminate"
                    v-model="checkAll"
                    @change="handleCheckAllChange">全选
            </el-checkbox>
            <div style="margin: 15px 0"></div>
            <el-checkbox-group
                    v-model="checkedRoles"
                    @change="handleCheckedRolesChange">
                <el-checkbox
                        v-for="role in roleList"
                        :label="role.roleId"
                        :key="role.roleId">{{ role.roleName }}
                </el-checkbox>
            </el-checkbox-group>
        </template>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="addUserAndRole">确 定</el-button>
        </div>
    </el-dialog>
    <!--添加或者更新的form表单-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="form">
            <!--<el-form-item label="部门ID" :label-width="formLabelWidth">
                <el-input v-model="form.deptId" autocomplete="off"></el-input>
            </el-form-item>-->
            <el-form-item label="登录账号" :label-width="formLabelWidth">
                <el-input v-model="form.loginName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" :label-width="formLabelWidth">
                <el-input v-model="form.userName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="用户类型" :label-width="formLabelWidth">
                <el-select v-model="form.userType" placeholder="用户类型">
                    <el-option label="00系统用户" value="0"></el-option>
                    <el-option label="其它系统用户" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="用户邮箱" :label-width="formLabelWidth">
                <el-input v-model="form.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="用户电话" :label-width="formLabelWidth">
                <el-input v-model="form.phoneNumber" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="用户性别" :label-width="formLabelWidth">
                <el-select v-model="form.sex" placeholder="用户性别">
                    <el-option label="男" value="0"></el-option>
                    <el-option label="女" value="1"></el-option>
                    <el-option label="未知" value="3"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="头像" :label-width="formLabelWidth">
                <!--<el-input v-model="form.avatar" autocomplete="off"></el-input>-->
                <!--上传组件-->
                <el-upload
                        class="avatar-uploader"
                        action="/user/uploadFile"
                        name="file2"
                        :show-file-list="false"
                        :on-success="handleFileSuccess"
                        :before-upload="beforeFileUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>

            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
                <el-input v-model="form.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="盐加密" :label-width="formLabelWidth">
                <el-input v-model="form.salt" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="账号状态" :label-width="formLabelWidth">
                <el-select v-model="form.status" placeholder="账号状态">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="停用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="删除标志" :label-width="formLabelWidth">
                <el-select v-model="form.delFlag" placeholder="删除标志">
                    <el-option label="存在" value="0"></el-option>
                    <el-option label="删除" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="最后登录IP" :label-width="formLabelWidth">
                <el-input v-model="form.loginIp" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="最后登录时间" :label-width="formLabelWidth">
                <el-input v-model="form.loginDate" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="创建者" :label-width="formLabelWidth">
                <el-input v-model="form.createBy" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="更新者" :label-width="formLabelWidth">
                <el-input v-model="form.updateBy" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input v-model="form.remark" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色ID" :label-width="formLabelWidth">
                <el-input v-model="form.roleId" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrUpdate">确 定</el-button>
        </div>
    </el-dialog>
</div>
<script>
    //let roleOpt=[{roleId:1,roleName:'管理员'},{roleId:5,roleName:'总经理'},{roleId:6,roleName:'商户'}];
    //js代码
    var vue = new Vue({
        el: "#app",
        data() { //存放使用的所有属性数据
            return { //方便编写表单校验

                tableData: [],//表格数据
                currentPage: 1,//页码 第几页
                pageSize: 2,//每页显示数量
                total: 100,//分页总数量
                searchForm: {
                    deptId: '',
                    loginName: '',
                    userName: '',
                    userType: '',
                    email: '',
                    phoneNumber: '',
                    sex: '',
                    avatar: '',
                    password: '',
                    salt: '',
                    status: '',
                    delFlag: '',
                    loginIp: '',
                    loginDate: '',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: ''
                },//封装查询对象
                dialogFormVisible: false,//是否显示对话框
                title: '用户添加',//默认显示title
                form: {
                    deptId: '',
                    loginName: '',
                    userName: '',
                    userType: '',
                    email: '',
                    phoneNumber: '',
                    sex: '',
                    avatar: '',
                    password: '',
                    salt: '',
                    status: '',
                    delFlag: '',
                    loginIp: '',
                    loginDate: '',
                    createBy: '',
                    createTime: '',
                    updateBy: '',
                    updateTime: '',
                    remark: ''
                }, //form表单
                formLabelWidth: '120px',//labal宽度
                //roleList:[{roleId:1,roleName:'管理员'},{roleId:5,roleName:'总经理'},{roleId:6,roleName:'商户'}],
                roleList: [],
                rolesVisible: false,
                //checkedRoles:[1,5],
                checkedRoles: [],
                checkAll: false,
                roleIds: "",
                userId: 0,
                isIndeterminate: true,
                imageUrl: '',//图片回显Url地址
            }
        },
        created: function () {//页面初始化时，需要执行的业务可以放入该方法
            //调用加载数据方法
            this.loadData();
            this.leadAllRole();
        },
        methods: { //存放所有使用的方法（函数）
            //封装请求数据的方法
            loadData() {
                //定义变量_this=this
                var _this = this;
                //axios向后台发请求
                axios.post('/user/all', //请求的url
                    {
                        "pageNo": this.currentPage, "pageSize": this.pageSize,
                        "data": {
                            "userName": this.searchForm.userName,
                            "remark": this.searchForm.remark
                        }
                    })//请求参数  json格式
                    .then(function (response) {//回调函数
                        //前端控制台打印  response 是json对象
                        console.log(response);
                        console.log(JSON.stringify(response));
                        //response获取后台数据时，一定加data  response.data相当于从响应的body中获取
                        if (response.data.code == 200) {
                            //这里面直接写this相当于axios对象 不是vue
                            // this.tableData = response.data.data.list; //错误的
                            _this.tableData = response.data.data.list;
                            _this.total = response.data.data.total;
                        }
                    })
                    .catch(function (error) {  //异常处理
                        console.log(error);
                    });
            },
            leadAllRole() {
                var _this = this;
                axios.post("/role/queryAll")
                    .then(function (response) {
                        if (response.data.code == 200) {
                            _this.roleList = response.data.data;
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        _this.$message.error("你错了。。。");
                    });
            },
            //每页数量发生变化
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                //调用加载数据方法
                this.loadData();
            },
            //页码（第几页）发生变化
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                //调用加载数据方法
                this.loadData();
            },
            //把系统用户数字转换成字符串
            getUserType(row, column, cellValue, index) {
                //cellValue status的值
                var returnValue = '';
                if (cellValue == 0) {
                    returnValue = "00系统用户";
                } else {
                    returnValue = "其他系统用户";
                }
                return returnValue;
                // return cellValue==1?"启动":"禁用";
            },
            //把性别数字转换成字符串
            getSex(row, column, cellValue, index) {
                //cellValue status的值
                var returnValue = '';
                if (cellValue == 0) {
                    returnValue = "男";
                } else if (cellValue == 1) {
                    returnValue = "女";
                } else {
                    returnValue = "未知";
                }
                return returnValue;
                // return cellValue==1?"启动":"禁用";
            },
            //把状态数字转换成字符串
            getStatus(row, column, cellValue, index) {
                //cellValue status的值
                var returnValue = '';
                if (cellValue == 0) {
                    returnValue = "正常";
                } else {
                    returnValue = "停用";
                }
                return returnValue;
                // return cellValue==1?"启动":"禁用";
            },
            //把删除状态数字转换成字符串
            getDelFlag(row, column, cellValue, index) {
                //cellValue status的值
                var returnValue = '';
                if (cellValue == 0) {
                    returnValue = "存在";
                } else {
                    returnValue = "删除";
                }
                return returnValue;
                // return cellValue==1?"启动":"禁用";
            },
            //搜索方法
            search() {
                this.loadData();
            },
            //跳转更新
            handleEdit(index, row) {
                console.log(index, row);
                //让对话框显示
                this.dialogFormVisible = true;
                //让title值也发生变化
                this.title = '用户更新';
                //给表单赋值
                this.form = row;
            },
            handleCheckAllChange(val) {
                // alert(val);
                if (val) {
                    // alert(JSON.stringify(this.roleList));
                    for (var i = 0; i < this.roleList.length; i++) {
                        //alert(this.roleList[i].roleId);
                        var tempRI = this.roleList[i].roleId;
                        this.checkedRoles.push(tempRI);
                        this.roleIds += tempRI + ",";
                    }
                    //去掉最后一个逗号
                    this.roleIds = this.roleIds.substr(0, this.roleIds.length - 1);
                    // alert(this.roleIds);
                } else {
                    this.checkedRoles = [];
                    this.roleIds = "";
                }
            },
            handleCheckedRolesChange(value) {
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.roleList.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
                this.roleIds = value;
            },
            //跳转添加
            handleAdd() {
                //让对话框显示
                this.dialogFormVisible = true;
                //让title值也发生变化
                this.title = '用户添加';
                //让form清空
                this.form = {};
            },
            //真正添加或者更新
            addOrUpdate() {
                //定义请求路径，默认是添加
                var uri = "/user/add";
                //判断是否是更新
                if (this.title == '用户更新') {
                    uri = "/user/update";
                }
                //定义变量_this=this
                var _this = this;
                //axios向后台发请求
                axios.post(uri, //请求的url
                    this.form)//请求参数  json格式
                    .then(function (response) {//回调函数
                        //前端控制台打印  response 是json对象
                        console.log(response);
                        console.log(JSON.stringify(response));
                        //response获取后台数据时，一定加data  response.data相当于从响应的body中获取
                        if (response.data.code == 200) {
                            //提示成功
                            _this.$message({
                                message: '恭喜你，这是一条成功消息',
                                type: 'success'
                            });
                            //关闭弹框
                            _this.dialogFormVisible = false;
                            //重新加载数据
                            _this.loadData();
                        } else {
                            _this.$message.error('错了哦，这是一条错误消息');
                        }
                    })
                    .catch(function (error) {//异常处理
                        console.log(error);
                    });
            },
            //处理删除
            handleDelete(index, row) {
                //定义请求路径，默认是添加
                var uri = "/user/deleteById";
                //定义变量_this=this
                var _this = this;
                this.form = row;
                //axios向后台发请求
                axios.post(uri, //请求的url
                    this.form)//请求参数  json格式
                    .then(function (response) {//回调函数
                        //前端控制台打印  response 是json对象
                        console.log(response);
                        console.log(JSON.stringify(response));
                        //response获取后台数据时，一定加data  response.data相当于从响应的body中获取
                        if (response.data.code == 200) {
                            //提示成功
                            _this.$message({
                                message: '恭喜你，这是一条成功消息',
                                type: 'success'
                            });

                            //重新加载数据
                            _this.loadData();
                        } else {
                            _this.$message.error('错了哦，这是一条错误消息');
                        }
                    })
                    .catch(function (error) {//异常处理
                        console.log(error);
                    });
            },
            addRole(index, row) {
                this.rolesVisible = true;
                var _this = this;
                this.form = row;
                this.userId = this.form.userId;
                axios.post('/role/queryRole', this.form)
                    .then(function (response) {//回调函数
                        //前端控制台打印  response 是json对象
                        console.log(response);
                        console.log(JSON.stringify(response));
                        //response获取后台数据时，一定加data  response.data相当于从响应的body中获取
                        if (response.data.code == 200) {
                            //提示成功
                            _this.$message({
                                message: '恭喜你，这是一条成功消息',
                                type: 'success'
                            });

                            _this.checkedRoles = response.data.data;
                            /* alert(_this.checkedRoles)*/

                        } else {
                            _this.$message.error('错了哦，这是一条错误消息');
                        }
                    })
                    .catch(function (error) {//异常处理
                        console.log(error);
                    });
            },
            //给用户添加角色
            addUserAndRole() {
                //判断是否有选中的 如果为0，说明没选中
                if (this.roleIds.length == 0) {
                    this.$message.error("至少选中一个角色。。。");
                    return;
                }
                if (this.userId == 1) {
                    var roleIdsArrray = this.roleIds.toString().split(",");
                    var tempRoleId = 0;
                    //roleIds="1,5,7,8,11,111"
                    for (var i = 0; i < roleIdsArrray.length; i++) {
                        if (roleIdsArrray[i] == 1) {
                            tempRoleId = 1;
                            break;
                        }
                    }
                    if (tempRoleId == 0) {
                        this.$message.error("管理员必须拥有管理员角色。。。");
                        return;
                    }
                }
                //保存数据
                var _this = this;
                console.log(this.userId);
                console.log(this.roleIds);
                axios.post(
                    "/role/updateRole", {"userId": this.userId, "roleIds": this.roleIds}
                )
                    .then(function (response) {
                        if (response.data.code == 200) {
                            //关闭弹框
                            _this.rolesVisible = false;
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        _this.$message.error("你错了。。。");
                    });
            },
            //处理文件成功后的回调方法
            handleFileSuccess(res, file) {
                //回显上传图片
                this.imageUrl = URL.createObjectURL(file.raw);
                //打印弹出file
                //alert(JSON.stringify(file));
                this.form.avatar = file.response.data.filePath;
                this.form.avatarname = file.response.data.fileOriginName;
                //  alert(JSON.stringify(this.form));
            },
            //文件上传前的处理方法
            beforeFileUpload(file) {
                //   isJPG = file.type 赋值操作 把图片类型赋值给isJPG   ==  比较值 例如 1=='1' 为true
                //       ===  比较类型  比较值   1==='1'  为false  类型不等
                //const isJPG = file.type === 'image/jpeg';
                //   file.size文件大小，单位是字节
                const isLt5M = file.size / 1024 / 1024 < 5;

                /*if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }*/
                if (!isLt5M) {
                    this.$message.error('上传头像图片大小不能超过 5MB!');
                }
                //返回false不会执行
                return isLt5M;
            },
        }
    })
</script>
</body>
</html>
